﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common.Utility
{

    public class Tool
    {
        public Tool() { }
  
        /**
           * \brief string至byte转换
           * 
           * \param[in]  idString 字符串类型的ID值
           * \param[ref]  valid 字符是否可用标识
           */
        public static byte StringToByte(string idString, ref bool valid)
        {
            byte ret = byte.MaxValue;
            bool isHex = false;
            if (idString.StartsWith("0x") || idString.StartsWith("0X"))
            {
                isHex = true;
            }
            try
            {
                if (isHex)
                {
                    ret = Convert.ToByte(idString, 16);
                }
                else
                {
                    ret = Convert.ToByte(idString);
                }
            }
            catch (Exception)
            {
                valid = false;
            }
            return ret;
        }

        /**
         * \brief string至int转换
         * 
         * \param[in]  numberString 字符串类型的ID值
         * \param[ref]  valid 字符是否可用标识
         */
        public static int StringToInt32(string numberString, ref bool valid)
        {
            int ret = int.MaxValue;
            try
            {
                ret = Convert.ToInt32(numberString);
            }
            catch (Exception)
            {
                valid = false;
            }
            return ret;
        }

        /**
           * \brief string至double转换
           * 
           * \param[in]  numberString 字符串类型的ID值
           * \param[ref]  valid 字符是否可用标识
           */
        public static double StringToDouble(string numberString, ref bool valid)
        {
            double ret = 0;
            try
            {
                ret = Convert.ToDouble(numberString);
            }
            catch
            {
                valid = false;
            }
            return ret;
        }

        /**
           * \brief 除去数据中首位无效零的情况
           * 
           * \param[in]  numberString 数据字符串
           */
        public static void RemoveInvalidZero(ref string numberString)
        {
            if (numberString.Length > 1)
            {
                if ('0' == numberString[0] && '.' != numberString[1])
                {
                    numberString = numberString.Substring(1, numberString.Length - 1);
                }
            }
        }
    }
}
